package com.smart.home.multi;

import com.smart.home.netty.handler.AbstractChannelInboundHandler;
import com.smart.home.util.CommandDecoder;
import com.smart.home.util.CommandEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

/**
 * 客户端1处理
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-22
 */
@ChannelHandler.Sharable
public class Client1Handler extends AbstractChannelInboundHandler {

    private String userId = "userId";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String content = "9023123EDD00000001";
        byte[] decode = CommandEncoder.decode(content);
        ctx.writeAndFlush(Unpooled.copiedBuffer(decode));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String result = ByteBufUtil.hexDump(msg);
        System.out.println(result);
        String[] msgs = result.split("eeeeeeeeeeee");
        for (String mg : msgs) {
            System.out.println("接收信息："+ CommandDecoder.hexToStringGBK(mg)+"   ");
        }
        //String id = (String) ctx.channel().attr(AttributeKey.newInstance(userId)).get();
       // System.out.println("id:"+id);
        //System.out.println("客户端1接收信息："+msg.toString(CharsetUtil.UTF_8));
        System.out.println("----------------------------------------------------------");
       /* String content = msg.toString(CharsetUtil.UTF_8);
        System.out.println("【客户端】client1接收信息：" + content);
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);*/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端client1出现异常");
        cause.printStackTrace();
        ctx.close();
    }
}
